﻿/*
 *  PassBag is multi-platform software that securely manage/store passwords
 *  Copyright (C) <2009>  <Hugo Rodrigues PEREIRA>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *	
 *  You can find a copy of the GPLv3 at project <root directory>/gpl.txt
 *
 */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.IO;
using PassBag.Data;
using PassBag.Logic;
using PassBag.Presentation.Logic;
using PassBag.Presentation.Backup;
using PassBag.Logic.Settings;
using PassBag.Logic.RecentFiles;
using PassBag.Presentation.Controls;

namespace PassBag.Presentation {
    public partial class MainForm : Form {
        // manage lock, unlock and recent files
        private enum ShowMode { 
            RecentFile = 1,
            Unlock,
            PasswordList
        }
        private ShowMode _showMode = ShowMode.PasswordList;
        UnlockFileControl unlockFile = new UnlockFileControl();
        StartPageControl startPage = new StartPageControl();
        private bool _isLocked;
        private string _lastCopiedPassword = string.Empty;

        private const string DEFAULT_LANGUAGE = "";
        //private const string CST_DEFAULT_LANGUAGE = "fr-CH";
        private const string PASSWORD_ITEM = "passbag";
        // image key for the ListView
        public const string STAR_IMAGE_KEY = "star";
        private const string INCOMPLETE_IMAGE_KEY = "incomplete";
        // filter listview backcolor, fore color and font
        private readonly Color BACK_FILTER_COLOR = Color.Orange;
        private readonly Color FORE_FILTER_COLOR = Color.DarkBlue;
        private readonly Color BACK_DEFAULT_COLOR = Color.FromName ("Window");
        private readonly Color FORE_DEFAULT_COLOR = Color.FromName ("WindowText");
        private Font _defaultItemFont = null;
        private Font _filterItemFont = null;

        // variable to manage the current file
        private bool _isFileEmpty = false;
        private bool _isFileOpen = false;
        private string _fileName = "Untitled";
        private string _filePath = string.Empty;
        private string _filePassword = string.Empty;
        List<PasswordObject> _passwordList = new List<PasswordObject>();
        private RecentFileList _recentFile = new RecentFileList();

        public MainForm () {
            InitializeComponent ();

            SetCurrentCulture ();
            LoadResource ();

            // intialize menu
            PrepareMenuAndToolBar ();

            ClearDocument ();
            
            SetReadOnlyState (true);

            InitRecentFileMenu ();

            // init filter item font
            InitFilterFont ();

            InitModeControls();
            UpdateShowMode(ShowMode.RecentFile);

            _isLocked = false;
            UpdateLockTimer();
        }

        #region Multi-language management
        private static void SetCurrentCulture () {
            CultureInfo ci = new System.Globalization.CultureInfo (DEFAULT_LANGUAGE);
            System.Threading.Thread.CurrentThread.CurrentUICulture = ci;
            System.Threading.Thread.CurrentThread.CurrentCulture = ci;
        }

        private void LoadResource () {
            this.Text = GetNewFileName ();
            
            menuFileNewToolStripMenuItem.Text = Properties.Resources.MainForm_MenuFileNew;
            menuFileOpenToolStripMenuItem.Text = Properties.Resources.MainForm_MenuFileOpen;
            menuFileOpenRecentToolStripMenuItem.Text = Properties.Resources.MainForm_MenuFileOpenRecent;
            menuFileSaveAsToolStripMenuItem.Text = Properties.Resources.MainForm_MenuFileSaveAs;
            menuFilePropertiesToolStripMenuItem.Text = Properties.Resources.MainForm_MenuFileProperties;
            menuFileSyncToolStripMenuItem.Text = Properties.Resources.MainForm_MenuFileSync;
            menuFileBackupToolStripMenuItem.Text = Properties.Resources.MainForm_MenuFileBackup;
            menuFileBackupBackupToolStripMenuItem.Text = Properties.Resources.MainForm_MenuFileBackupBackup;
            menuFileBackupRestoreToolStripMenuItem.Text = Properties.Resources.MainForm_MenuFileBackupRestore;
            menuFileChgPassToolStripMenuItem.Text = Properties.Resources.MainForm_MenuFileChgPass;
            menuFileExitToolStripMenuItem.Text = Properties.Resources.MainForm_MenuFileExit;
            menuEditEditToolStripMenuItem.Text = Properties.Resources.MainForm_MenuEditEdit;
            menuEditAddToolStripMenuItem.Text = Properties.Resources.MainForm_MenuEditAdd;
            menuEditDelToolStripMenuItem.Text = Properties.Resources.MainForm_MenuEditDel;
            menuEditDuplicateToolStripMenuItem.Text = Properties.Resources.MainForm_MenuEditDuplicate;
            menuEditCopyUserToolStripMenuItem.Text = Properties.Resources.MainForm_MenuEditCopyUser;
            menuEditCopyPasswordToolStripMenuItem.Text = Properties.Resources.MainForm_MenuEditCopyPassword;
            menuEditNavigateURLToolStripMenuItem.Text = Properties.Resources.MainForm_MenuEditNavigateURL;
            menuHelpSummaryToolStripMenuItem.Text = Properties.Resources.MainForm_MenuHelpSummary;
            menuHelpCheckForUpdateToolStripMenuItem.Text = Properties.Resources.MainForm_MenuHelpCheckForUpdate;
            menuHelpReportABugToolStripMenuItem.Text = Properties.Resources.MainForm_MenuHelpReportABug;
            menuHelpAboutToolStripMenuItem.Text = Properties.Resources.MainForm_MenuHelpAbout;

            filterToolStripLabel.Text = Properties.Resources.MainForm_FilterText;

            this.starredColumnHeader.Text = Properties.Resources.MainForm_StarredColumnHeader;
            this.titleColumnHeader.Text = Properties.Resources.MainForm_TitleColumnHeader;
            this.userColumnHeader.Text = Properties.Resources.MainForm_UserColumnHeader;
            this.urlColumnHeader.Text = Properties.Resources.MainForm_UrlColumnHeader;
            this.commentColumnHeader.Text = Properties.Resources.MainForm_CommentColumnHeader;
            this.lastModifiedcolumnHeader.Text = Properties.Resources.MainForm_LastModifiedcolumnHeader;

            cmMenuEditEditToolStripMenuItem.Text = Properties.Resources.MainForm_MenuEditEdit;
            cmMenuEditAddToolStripMenuItem.Text = Properties.Resources.MainForm_MenuEditAdd;
            cmMenuEditDelToolStripMenuItem.Text = Properties.Resources.MainForm_MenuEditDel;
            cmMenuEditDuplicateToolStripMenuItem.Text = Properties.Resources.MainForm_MenuEditDuplicate;
            cmMenuEditCopyUserToolStripMenuItem.Text = Properties.Resources.MainForm_MenuEditCopyUser;
            cmMenuEditCopyPasswordToolStripMenuItem.Text = Properties.Resources.MainForm_MenuEditCopyPassword;
            cmMenuEditNavigateURLToolStripMenuItem.Text = Properties.Resources.MainForm_MenuEditNavigateURL;

            

        } 
        #endregion
       
        #region misc methods
        private string GetNewFileName () {
            return string.Format ("{0} - {1}", Properties.Resources.Global_ApplicationName, Properties.Resources.MainForm_NewFileName);
        }


        private void UpdateWindowTitle () {
            if (!_isFileOpen) {
                this.Text = Properties.Resources.Global_ApplicationName;
            }
            else {
                this.Text = string.Format ("{0} - {1}", Properties.Resources.Global_ApplicationName, _fileName);
            }
        } 
        #endregion

        #region menu and toolbar 
        /// <summary>
        /// Apply menu and toolbar settings according to _isNewFile, _isLocked, _isFileEmpty and isFileOpen
        /// </summary>
        private void ApplyMenuSettings () {

            if (_isFileOpen && !_isLocked) {
                menuFileSaveAsToolStripMenuItem.Enabled = true;
                menuFileSyncToolStripMenuItem.Enabled = true;
                menuFileBackupToolStripMenuItem.Enabled = true;
                menuFileChgPassToolStripMenuItem.Enabled = true;
                menuEditAddToolStripMenuItem.Enabled = true;
                cmMenuEditAddToolStripMenuItem.Enabled = true;

                readOnlyToolStripButton.Enabled = true;

                if (_isFileEmpty) {
                    menuFileBackupBackupToolStripMenuItem.Enabled = false;
                    menuFileBackupRestoreToolStripMenuItem.Enabled = true;

                    menuEditEditToolStripMenuItem.Enabled = false;
                    cmMenuEditEditToolStripMenuItem.Enabled = false;
                    menuEditDelToolStripMenuItem.Enabled = false;
                    cmMenuEditDelToolStripMenuItem.Enabled = false;
                    menuEditDuplicateToolStripMenuItem.Enabled = false;
                    cmMenuEditDuplicateToolStripMenuItem.Enabled = false;
                    menuEditCopyUserToolStripMenuItem.Enabled = false;
                    cmMenuEditCopyUserToolStripMenuItem.Enabled = false;
                    menuEditCopyPasswordToolStripMenuItem.Enabled = false;
                    cmMenuEditCopyPasswordToolStripMenuItem.Enabled = false;
                    menuEditNavigateURLToolStripMenuItem.Enabled = false;
                    cmMenuEditNavigateURLToolStripMenuItem.Enabled = false;

                    starToolStripButton.Enabled = false;
                    clearToolStripButton.Enabled = false;
                    filterToolStripTextBox.Enabled = false;
                }
                else {
                    menuFileBackupBackupToolStripMenuItem.Enabled = true;
                    menuFileBackupRestoreToolStripMenuItem.Enabled = true;

                    menuEditEditToolStripMenuItem.Enabled = true;
                    cmMenuEditEditToolStripMenuItem.Enabled = true;
                    menuEditDelToolStripMenuItem.Enabled = true;
                    cmMenuEditDelToolStripMenuItem.Enabled = true;
                    menuEditDuplicateToolStripMenuItem.Enabled = true;
                    cmMenuEditDuplicateToolStripMenuItem.Enabled = true;
                    menuEditCopyUserToolStripMenuItem.Enabled = true;
                    cmMenuEditCopyUserToolStripMenuItem.Enabled = true;
                    menuEditCopyPasswordToolStripMenuItem.Enabled = true;
                    cmMenuEditCopyPasswordToolStripMenuItem.Enabled = true;
                    menuEditNavigateURLToolStripMenuItem.Enabled = true;
                    cmMenuEditNavigateURLToolStripMenuItem.Enabled = true;

                    starToolStripButton.Enabled = true;
                    clearToolStripButton.Enabled = true;
                    filterToolStripTextBox.Enabled = true;
                }

                // read only
                if (readOnlyToolStripButton.CheckState == CheckState.Checked) {
                    menuFileSyncToolStripMenuItem.Enabled = false;
                    menuFileChgPassToolStripMenuItem.Enabled = false;
                    menuEditAddToolStripMenuItem.Enabled = false;
                    cmMenuEditAddToolStripMenuItem.Enabled = false;
                    menuEditEditToolStripMenuItem.Enabled = false;
                    cmMenuEditEditToolStripMenuItem.Enabled = false;
                    menuEditDelToolStripMenuItem.Enabled = false;
                    cmMenuEditDelToolStripMenuItem.Enabled = false;
                    menuEditDuplicateToolStripMenuItem.Enabled = false;
                    cmMenuEditDuplicateToolStripMenuItem.Enabled = false;
                }
            }
            else { // file closed
                PrepareMenuAndToolBar ();
            }
        }

        private void InitAllMenuToolBarToEnabled () {
            // menu
            foreach (ToolStripMenuItem t_oMenuItem in ((ToolStrip)mainMenuStrip).Items)
                foreach (ToolStripItem t_oToolStripItem in t_oMenuItem.DropDownItems)
                    if (t_oToolStripItem.GetType () == typeof (ToolStripMenuItem)) {
                        t_oToolStripItem.Enabled = true;
                    }

            foreach (ToolStripItem toolStrip in ((ToolStrip)mainToolStrip).Items)
                if (toolStrip.GetType () == typeof (ToolStripButton)
                    || toolStrip.GetType () == typeof (ToolStripTextBox)) {
                    toolStrip.Enabled = true;
                    }

            // context menu
            foreach (ToolStripItem toolStrip in ((ToolStrip)passwordListContextMenu).Items)
                if (toolStrip.GetType () == typeof (ToolStripButton)
                    || toolStrip.GetType () == typeof (ToolStripTextBox)) {
                    toolStrip.Enabled = true;
                }
        }

        
        private void PrepareMenuAndToolBar () {
            // set all menu and toolbat to enabled
            InitAllMenuToolBarToEnabled ();

            // menu
            menuFileSaveAsToolStripMenuItem.Enabled = false;
            menuFileSyncToolStripMenuItem.Enabled = false;
            menuFileBackupToolStripMenuItem.Enabled = true;
            menuFileBackupBackupToolStripMenuItem.Enabled = false;
            menuFileBackupRestoreToolStripMenuItem.Enabled = true;
            menuFileChgPassToolStripMenuItem.Enabled = false;

            menuEditEditToolStripMenuItem.Enabled = false;
            menuEditAddToolStripMenuItem.Enabled = false;
            menuEditDelToolStripMenuItem.Enabled = false;
            menuEditDuplicateToolStripMenuItem.Enabled = false;
            menuEditCopyUserToolStripMenuItem.Enabled = false;
            menuEditCopyPasswordToolStripMenuItem.Enabled = false;
            menuEditNavigateURLToolStripMenuItem.Enabled = false;

            starToolStripButton.Enabled = false;
            readOnlyToolStripButton.Enabled = false;
            clearToolStripButton.Enabled = false;
            filterToolStripTextBox.Enabled = false;

            // context menu
            cmMenuEditEditToolStripMenuItem.Enabled = false;
            cmMenuEditAddToolStripMenuItem.Enabled = false;
            cmMenuEditDelToolStripMenuItem.Enabled = false;
            cmMenuEditDuplicateToolStripMenuItem.Enabled = false;
            cmMenuEditCopyUserToolStripMenuItem.Enabled = false;
            cmMenuEditCopyPasswordToolStripMenuItem.Enabled = false;
            cmMenuEditNavigateURLToolStripMenuItem.Enabled = false;
        }

        private void AfterEdit () {
            UpdateFileEmpty ();

            SavePasswordListToXMLFile (GetFullFileName());

            LoadCurrentFile ();
        }

        private void LoadCurrentFile () {
            // clear filter
            ClearFilter ();

            // reload listview
            ReloadListView ();

            ApplyMenuSettings ();
        }

        private void UpdateFileEmpty () {
            // list view not empty
            if (_passwordList.Count > 0) {
                _isFileEmpty = false;
            }
            else { // list view is empty
                _isFileEmpty = true;
            }
        }

        private string GetFullFileName () {
            if (! string.IsNullOrEmpty(_fileName) && ! string.IsNullOrEmpty(_filePath)) {
                return _filePath + System.IO.Path.DirectorySeparatorChar + _fileName;
            }
            else {
                throw new FileNotFoundException("Malformed file name");
            }
        }


        #endregion

        #region file new open save

        private void ClearDocument () {
            ClearDocument (true);
        }

        /// <summary>
        /// Clear the document and resets all tracking variables (_isNewFile and _isFileEmpty)
        /// </summary>
        private void ClearDocument (bool noFileOpen) {
            this.mainListView.Items.Clear();
            _passwordList.Clear ();
            _fileName = string.Empty;
            _filePath = string.Empty;
            _isFileOpen = false;
            _filePassword = string.Empty;

            if (noFileOpen) {
                ShowTimedStatusBarMessage (Properties.Resources.MainForm_StatusBarNoFileCreated); 
            }
            else {
                ShowTimedStatusBarMessage (Properties.Resources.MainForm_StatusBarFileOpened);
            }

            UpdateWindowTitle ();

            ApplyMenuSettings ();
        }

        /// <summary>
        /// Open document and prompt user for filename
        /// </summary>
        /// <returns>Return true if opened, otherwise false</returns>
        private bool OpenDocument () {
            return OpenDocument (string.Empty);
        }

        /// <summary>
        /// Open document and prompt user for filename
        /// </summary>
        /// <remarks>if openFileName is not empty, try to open without show dialog</remarks>
        /// <returns>Return true if opened, otherwise false</returns>
        private bool OpenDocument (string openFileName) {
            OpenFileDialog dlgOpen = new OpenFileDialog ();
            string newfilename = string.Empty;
            bool showDialog = string.IsNullOrEmpty (openFileName);
            bool success = false;

            if (showDialog) {
                dlgOpen.DefaultExt = XmlSettingsManager.Settings.FileExtension;

                dlgOpen.Filter = string.Format (Properties.Resources.Global_FileDialogFilter, XmlSettingsManager.Settings.FileExtension);
                dlgOpen.FilterIndex = 1; 
            }

            if (!showDialog || dlgOpen.ShowDialog () == DialogResult.OK) {

                if (showDialog) {
                    newfilename = dlgOpen.FileName;    
                }
                else {
                    newfilename = openFileName;    
                }
                

                EnterPasswordDialog passwordDialog = new EnterPasswordDialog ();

                if (passwordDialog.ShowDialog () == DialogResult.OK) {

                    if (CheckFilePassword(newfilename, passwordDialog.Password)) {
                        ClearDocument (false);
                        _filePassword = passwordDialog.Password;

                        try {
                            ReadXMLFileToPasswordList (newfilename, _filePassword);
                            _isFileOpen = true;
                            SetReadOnlyState (true);
                            UpdateFileEmpty ();
                            ApplyMenuSettings ();

                            UpdateFileInformation (newfilename);
                            UpdateWindowTitle ();

                            success = true;
                        }
                        catch (IOException ioEx) {
                            success = false;
                            MessageDialog.ShowError (this, string.Format (Properties.Resources.MainForm_MsgCreateFileError, ioEx.Message));
                        }
                        catch (Exception ex) {
                            success = false;
                            MessageDialog.ShowError (this, string.Format (Properties.Resources.MainForm_MsgCreateFileError, ex.Message));
                        }                        
                    }
                    else {
                        success = false;
                        MessageDialog.ShowError (this, Properties.Resources.MainForm_MsgPassNotMatchError);
                    }
                }
            }
            else // user cancel open
			{
                return success;
            }

            return success;
        }

        /// <summary>
        /// Get file information from full file name
        /// </summary>
        /// <param name="fileName">Full file name</param>
        private void UpdateFileInformation (string fileName) {
            //get the new file'fromString information
            FileInfo fi = new FileInfo (fileName);
            _fileName = fi.Name;
            _filePath = fi.Directory.FullName;

            UpdateRecentFileList (fileName);
        }

        /// <summary>
        /// SaveAs a document
        /// </summary>
        private bool SaveAsDocument () {
            string newfilename = string.Empty;

            SaveFileDialog dlgSave = new SaveFileDialog ();
            dlgSave.DefaultExt = XmlSettingsManager.Settings.FileExtension;
            dlgSave.Filter = string.Format (Properties.Resources.Global_FileDialogFilter, XmlSettingsManager.Settings.FileExtension); 

            dlgSave.FilterIndex = 1;

            //show dialog and check result
            if (dlgSave.ShowDialog () == DialogResult.OK) {
                newfilename = dlgSave.FileName;

                SavePasswordListToXMLFile (newfilename);

                _isFileOpen = true;
                ApplyMenuSettings ();

                UpdateFileInformation (newfilename);
                UpdateWindowTitle ();

                return true;
            }
            else // dlgSave.ShowDialog() Not OK
			{
                //user pressed Cancel, exit function
                return false;
            }

        }

        #endregion

        #region menu file 

        private void menuFileNewToolStripMenuItem_Click (object sender, EventArgs e) {
            // ask for new file name
            string newfilename = string.Empty;

            SaveFileDialog dlgSave = new SaveFileDialog ();
            dlgSave.DefaultExt = XmlSettingsManager.Settings.FileExtension;
            dlgSave.Filter = string.Format (Properties.Resources.Global_FileDialogFilter, XmlSettingsManager.Settings.FileExtension);
            //dlgSave.OverwritePrompt = true;
            dlgSave.FilterIndex = 1;

            if (dlgSave.ShowDialog () == DialogResult.OK) {
                newfilename = dlgSave.FileName;

                NewPasswordDialog passwordDialog = new NewPasswordDialog ();

                if (passwordDialog.ShowDialog () == DialogResult.OK) {

                    ClearDocument (false);
                    _filePassword = passwordDialog.Password;  
                    
                    try {
                        SavePasswordListToXMLFile (newfilename);
                        _isFileEmpty = true;
                        _isFileOpen = true;
                        SetReadOnlyState (false);
                        ApplyMenuSettings ();

                        UpdateFileInformation (newfilename); 
                        UpdateWindowTitle ();

                        UpdateShowMode(ShowMode.PasswordList);

                    }
                    catch (IOException ioEx) {
                        MessageDialog.ShowError (this, string.Format (Properties.Resources.MainForm_MsgPassNotMatchError, ioEx.Message));
                    }
                    catch (Exception ex) {
                        MessageDialog.ShowError (this, string.Format (Properties.Resources.MainForm_MsgPassNotMatchError, ex.Message));
                    }
                }

            }
        }

        private void menuFileOpenToolStripMenuItem_Click (object sender, EventArgs e) {
            if (OpenDocument ()) {
                UpdateShowMode(ShowMode.PasswordList);
            }
        } 

        private void menuFileOpenRecentFile1ToolStripMenuItem_Click (object sender, EventArgs e) {
            if (OpenDocument (menuFileOpenRecentFile1ToolStripMenuItem.Text)) {
                UpdateShowMode(ShowMode.PasswordList);
                UpdateLockTimer();
            }
        }

        private void menuFileOpenRecentFile2ToolStripMenuItem_Click (object sender, EventArgs e) {
            if (OpenDocument(menuFileOpenRecentFile2ToolStripMenuItem.Text)) {
                UpdateShowMode(ShowMode.PasswordList);
                UpdateLockTimer();
            }
        }

        private void menuFileOpenRecentFile3ToolStripMenuItem_Click (object sender, EventArgs e) {
            if (OpenDocument(menuFileOpenRecentFile3ToolStripMenuItem.Text)) {
                UpdateShowMode(ShowMode.PasswordList);
                UpdateLockTimer();
            }
        }

        private void menuFileOpenRecentFile4ToolStripMenuItem_Click (object sender, EventArgs e) {
            if (OpenDocument(menuFileOpenRecentFile4ToolStripMenuItem.Text)) {
                UpdateShowMode(ShowMode.PasswordList);
                UpdateLockTimer();
            }
        }

        private void menuFileOpenRecentFile5ToolStripMenuItem_Click (object sender, EventArgs e) {
            if (OpenDocument(menuFileOpenRecentFile5ToolStripMenuItem.Text)) {
                UpdateShowMode(ShowMode.PasswordList);
                UpdateLockTimer();
            }
        }

        private void menuFileOpenRecentClearToolStripMenuItem_Click (object sender, EventArgs e) {
            ClearRecentFileMenu ();
        }

        private void menuFileSaveAsToolStripMenuItem_Click (object sender, EventArgs e) {
            SaveAsDocument();
        }

        private void menuFilePropertiesToolStripMenuItem_Click (object sender, EventArgs e) {
            SettingDialog settingsDialog = new SettingDialog ();
            settingsDialog.ShowDialog ();
        }

        private void menuFileSyncToolStripMenuItem_Click (object sender, EventArgs e) {
            string comparedFileName = string.Empty;
            string comparedFilePassword = string.Empty;


            OpenFileDialog dlgOpen = new OpenFileDialog ();
            dlgOpen.DefaultExt = XmlSettingsManager.Settings.FileExtension;
            dlgOpen.Filter = string.Format (Properties.Resources.Global_FileDialogFilter, XmlSettingsManager.Settings.FileExtension);
            dlgOpen.FilterIndex = 1;

            if (dlgOpen.ShowDialog () == DialogResult.OK) {
                comparedFileName = dlgOpen.FileName;

                EnterPasswordDialog passwordDialog = new EnterPasswordDialog ();

                // active and compared file are different ?
                if (! GetFullFileName().Equals(comparedFileName)) { 
                    if (passwordDialog.ShowDialog () == DialogResult.OK) {

                        if (CheckFilePassword (comparedFileName, passwordDialog.Password)) {
                            comparedFilePassword = passwordDialog.Password;

                            SynchronizeFilesDialog synnchDialog = new SynchronizeFilesDialog ();

                            synnchDialog.ActiveFile = GetFullFileName ();
                            synnchDialog.ActiveFilePassword = _filePassword;
                            synnchDialog.ComparedFile = comparedFileName;
                            synnchDialog.ComparedFilePassword = comparedFilePassword;

                            DialogResult result;

                            if ((result = synnchDialog.ShowDialog ()) == DialogResult.OK) {
                                ClearFilter ();
                                this.mainListView.Items.Clear ();
                                _passwordList.Clear ();
                                ReadXMLFileToPasswordList (GetFullFileName (), _filePassword);
                                UpdateFileEmpty ();
                                ApplyMenuSettings ();
                            }

                            if (result == DialogResult.OK || result == DialogResult.Ignore) {
                                ShowTimedStatusBarMessage (Properties.Resources.MainForm_StatusBarSyncSuccess);    
                            }

                            
                        }
                        else {
                            MessageDialog.ShowError (this, Properties.Resources.MainForm_MsgPassNotMatchError); // idem string opendocument
                        }

                    } 
                }
                else {
                    MessageDialog.ShowError (this, Properties.Resources.MainForm_MsgCanCompareSameError); // idem string opendocument
                }

            }
        }

        private void menuFileBackupBackupToolStripMenuItem_Click (object sender, EventArgs e) {
            using (BackupSetAddDialog backupFile = new BackupSetAddDialog ()) {
                backupFile.CurrentPasswordFile = GetFullFileName ();

                if (backupFile.ShowDialog () == DialogResult.OK) {
                    ShowTimedStatusBarMessage (Properties.Resources.MainForm_StatusBarBackupOK);
                }
            }
        }

        private void menuFileBackupRestoreToolStripMenuItem_Click (object sender, EventArgs e) {
            using (BackupSetRestoreDialog restoreFile = new BackupSetRestoreDialog ()) {
                restoreFile.CurrentPasswordFile = GetFullFileName ();

                if (restoreFile.ShowDialog () == DialogResult.OK) {
                    ShowTimedStatusBarMessage (Properties.Resources.MainForm_StatusBarRestoreOK);
                }
            }
        }

        private void menuFileChgPassToolStripMenuItem_Click (object sender, EventArgs e) {
            ChangePasswordDialog changePasswordDialog = new ChangePasswordDialog ();

            changePasswordDialog.CurrentPassword = _filePassword;
            changePasswordDialog.ShowDialog (this);
            

            if (changePasswordDialog.DialogResult == DialogResult.OK) {
                _filePassword = changePasswordDialog.Password;
                
                AfterEdit ();
            }
        }

        private void menuFileExitToolStripMenuItem_Click (object sender, EventArgs e) {
            this.Close ();
        }

        #endregion

        #region menu edit

        private void menuEditEditToolStripMenuItem_Click (object sender, EventArgs e) {
            Guid selectedGuid = GetSelectedPasswordObject ();

            if (selectedGuid != Guid.Empty) {
                PasswordObject selectedPasswordObject = FindPasswordObject (selectedGuid);

                EditPasswordDialog editPassDialog = new EditPasswordDialog (selectedPasswordObject);

                if (editPassDialog.ShowDialog () == DialogResult.OK) {

                    _passwordList[_passwordList.IndexOf (selectedPasswordObject)] = editPassDialog.PasswordObject;

                    AfterEdit ();
                }
            }
            else {
                MessageDialog.ShowError (this, Properties.Resources.MainForm_MsgSelectItemFirstError);
            }

        }

        private void menuEditAddToolStripMenuItem_Click (object sender, EventArgs e) {
            EditPasswordDialog editPassDialog = new EditPasswordDialog ();

            if (editPassDialog.ShowDialog () == DialogResult.OK) {
                _passwordList.Add (editPassDialog.PasswordObject);

                AfterEdit ();
            }
        }

        private void menuEditDelToolStripMenuItem_Click (object sender, EventArgs e) {
            if (MessageDialog.ShowQuestion (this, Properties.Resources.MainForm_MsgSureToDeleteQuestion)) {
                Guid selectedGuid = GetSelectedPasswordObject ();

                if (selectedGuid != Guid.Empty) {
                    PasswordObject selectedPasswordObject = FindPasswordObject(selectedGuid);

                    _passwordList.Remove (selectedPasswordObject);

                    AfterEdit ();

                }
                else {
                    MessageDialog.ShowError (this, Properties.Resources.MainForm_MsgSelectItemFirstError);
                }

            }
        }

        private void menuEditDuplicateToolStripMenuItem_Click (object sender, EventArgs e) {
            Guid selectedGuid = GetSelectedPasswordObject ();

            if (selectedGuid != Guid.Empty) {
                PasswordObject selectedPasswordObject = (PasswordObject)FindPasswordObject (selectedGuid).Clone ();

                selectedPasswordObject.Id = Guid.NewGuid ();

                _passwordList.Add (selectedPasswordObject);

                AfterEdit ();

            }
            else {
                MessageDialog.ShowError (this, Properties.Resources.MainForm_MsgSelectItemFirstError);
            }
        }

        private void menuEditCopyUserToolStripMenuItem_Click (object sender, EventArgs e) {
            CopyUserNameToClipboard ();
        }

        private void menuEditCopyPasswordToolStripMenuItem_Click (object sender, EventArgs e) {
            CopyPasswordToClipboard ();
        }

        private void menuEditNavigateURLToolStripMenuItem_Click (object sender, EventArgs e) {
            NavigateToURL ();
        }
        #endregion

        #region menu help
        private void menuHelpSummaryToolStripMenuItem_Click (object sender, EventArgs e) {

        }

        private void menuHelpAboutToolStripMenuItem_Click (object sender, EventArgs e) {
            AboutBoxForm aboutDialog = new AboutBoxForm ();
            aboutDialog.ShowDialog ();
        }

        private void menuHelpCheckForUpdateToolStripMenuItem_Click (object sender, EventArgs e) {
            PassBag.Utils.WebTools.Navigate (Properties.Resources.MainForm_MenuHelpCheckForUpdateLink);
        }

        private void menuHelpReportABugToolStripMenuItem_Click (object sender, EventArgs e) {
            PassBag.Utils.WebTools.Navigate (Properties.Resources.MainForm_MenuHelpReportABugLink);
        }

        #endregion

        #region toolStrip events
        private void starToolStripButton_Click (object sender, EventArgs e) {
            UpdateStarOnSelection ();
        }

        private void readOnlyToolStripButton_Click (object sender, EventArgs e) {
            // inverse check state
            SetReadOnlyState (readOnlyToolStripButton.CheckState == CheckState.Checked ? false : true);
        }

        private void filterToolStripTextBox_KeyUp (object sender, KeyEventArgs e) {
            string filter = filterToolStripTextBox.Text;

            if (string.IsNullOrEmpty (filter)) {
                ClearFilter ();
            }
            else {
                FilterItems (filter);
            }
        }

        private void clearToolStripButton_Click (object sender, EventArgs e) {
            ClearFilter ();
        } 
        #endregion

        #region list view and password list helpers 

        // Search predicate returns true if a string ends in "saurus".
        private PasswordObject FindPasswordObject (Guid guid) {
            PasswordObject pass = null;

            foreach (PasswordObject item in _passwordList) {
                if (item.Id.Equals(guid)) {
                    pass = item;    
                }    
            }

            return pass;
        }

  
        private void ReloadListView () {
            this.mainListView.Items.Clear ();

            foreach (PasswordObject password in _passwordList) {
                ListViewItem item = this.mainListView.Items.Add (password.Id.ToString (), string.Empty, password.Information);
                item.Tag = password.Password;
                item.SubItems.Add (password.Title);
                item.SubItems.Add (password.UserName);
                item.SubItems.Add (password.Url);
                item.SubItems.Add (password.Comment);
                item.SubItems.Add (password.LastModified.ToString ());
            }
        }

        private bool AddPasswordToListView (PasswordObject password) {
            try {
                ListViewItem item = this.mainListView.Items.Add (password.Id.ToString (), string.Empty, password.Information);
                item.Tag = password.Password;
                item.SubItems.Add (password.Title);
                item.SubItems.Add (password.UserName);
                item.SubItems.Add (password.Url);
                item.SubItems.Add (password.Comment);
                item.SubItems.Add (password.LastModified.ToString ());

                this.mainListView.Items.Add (item);

                return true;
            }
            catch {
                return false;
            }
        }

        private Guid GetSelectedPasswordObject () {
            if (mainListView.Items.Count > 0) {

                if (mainListView.SelectedItems.Count > 0) {
                    Guid selectedId = new Guid (mainListView.SelectedItems[0].Name);
                    return selectedId;
                }
                else {
                    return Guid.Empty;
                }
            }
            else {
                return Guid.Empty;
            }
        }


        #endregion

        #region open / save XML
        private void SavePasswordListToXMLFile (string filename) {
            List<PasswordObject> passwordList = new List<PasswordObject> ();

            passwordList.Add (PasswordItem.GetPasswordObjectFromPassword (_filePassword));

            if (_passwordList.Count > 0) {
                passwordList.AddRange (_passwordList);
            }

            /*
            for (int i = 0; i < mainListView.Items.Count; i++) {
                passwordList.AddFileToArchive (new PasswordObject (new Guid (this.mainListView.Items[i].Name),
                                       this.mainListView.Items[i].ImageKey,
                                       this.mainListView.Items[i].Tag.ToString (),
                                       this.mainListView.Items[i].SubItems[1].Text,
                                       this.mainListView.Items[i].SubItems[2].Text,
                                       this.mainListView.Items[i].SubItems[3].Text,
                                       this.mainListView.Items[i].SubItems[4].Text,
            }                           DateTime.Parse (this.mainListView.Items[i].SubItems[5].Text)));
             */

            List<PasswordCryptObject> passwordCryptList = new List<PasswordCryptObject> ();

            foreach (PasswordObject passwordObject in passwordList) {
                passwordCryptList.Add(EncryptPasswordObject.Encrypt (passwordObject, _filePassword));
                
            }

            ObjectSerializer.SerializeObject<List<PasswordCryptObject>> (filename, passwordCryptList);

            UpdateLockTimer();
        }

        /// <summary>
        /// Read XML file and check password
        /// </summary>
        /// <param name="filename">xml file</param>
        /// <param name="filePassword">password</param>
        /// <returns>true if successfull, else false</returns>
        private bool ReadXMLFileToPasswordList (string filename, string filePassword) {
            try {
                List<PasswordCryptObject> passwordCryptList = new List<PasswordCryptObject> ();
                List<PasswordObject> passwordList = new List<PasswordObject> ();

                passwordCryptList = ObjectSerializer.DeserializeObject<List<PasswordCryptObject>> (filename);

                foreach (PasswordCryptObject passwordObject in passwordCryptList) {
                    passwordList.Add (EncryptPasswordObject.Decrypt (passwordObject, _filePassword));
                }

                if (PasswordItem.GetPasswordStringFromPasswordObject (passwordList[0]).Equals (filePassword)) {
                    _filePassword = filePassword;
                    this.mainListView.Items.Clear ();
                    passwordList.Remove (passwordList[0]);

                    _passwordList.Clear ();
                    _passwordList.AddRange (passwordList);

                    ReloadListView ();

                    return true;
                }
                else {
                    return false;
                }
            }
            catch {
                this.mainListView.Items.Clear ();
                _passwordList.Clear ();

                return false;
            }


        }

        /// <summary>
        /// Check the file password
        /// </summary>
        /// <param name="filename">name of passbag file</param>
        /// <param name="filePassword">password to check</param>
        /// <returns>Return true if password is correct, else return false</returns>
        private bool CheckFilePassword (string filename, string filePassword) {
            try {
                List<PasswordCryptObject> passwordCryptList = new List<PasswordCryptObject> ();

                passwordCryptList = ObjectSerializer.DeserializeObject<List<PasswordCryptObject>> (filename);

                if (PasswordItem.GetPasswordStringFromPasswordObject (EncryptPasswordObject.Decrypt (passwordCryptList[0], filePassword)).Equals (filePassword)) {

                    return true;
                }
                else {
                    return false;
                }
            }
            catch {
                return false;
            }


        } 

        #endregion

        #region star item management
        private void UpdateStarOnSelection () {
            Guid selectedGuid = GetSelectedPasswordObject ();

            if (selectedGuid != Guid.Empty) {
                PasswordObject selectedPasswordObject = FindPasswordObject (selectedGuid);

                if (selectedPasswordObject.Information.Equals (STAR_IMAGE_KEY)) {
                    selectedPasswordObject.Information = string.Empty;

                    _passwordList[_passwordList.IndexOf (selectedPasswordObject)].Information = string.Empty;
                }
                else {
                    selectedPasswordObject.Information = STAR_IMAGE_KEY;

                    _passwordList[_passwordList.IndexOf (selectedPasswordObject)].Information = STAR_IMAGE_KEY;
                }

                AfterEdit ();
            }
            else {
                MessageDialog.ShowError (this, Properties.Resources.MainForm_MsgSelectItemFirstError);
            }
        }
        #endregion

        #region read only management

        /// <summary>
        /// Manage the read only or read write mode
        /// </summary>
        /// <remarks>
        /// The _isFileOpen must be set before call SetReadOnlyState
        /// </remarks>
        /// <param name="isReadOnly">True if read only and false for read write</param>
        private void SetReadOnlyState (bool isReadOnly) {
            if (isReadOnly == true) {
                readOnlyToolStripButton.CheckState = CheckState.Checked;
                readOnlyToolStripStatusLabel.BackgroundImage = statusBarImageList.Images["readonly"];
            }
            else {
                readOnlyToolStripButton.CheckState = CheckState.Unchecked;
                readOnlyToolStripStatusLabel.BackgroundImage = statusBarImageList.Images["readwrite"];
            }

            if (! _isFileOpen) {
                readOnlyToolStripStatusLabel.BackgroundImage = null;
            }

            ApplyMenuSettings ();
        }

        #endregion

        #region list view event's
        private void mainListView_MouseUp (object sender, MouseEventArgs e) {
            if (_isFileOpen && e.Button == MouseButtons.Right) {
                passwordListContextMenu.Show(mainListView, new Point (e.X, e.Y));
            }
        }

        private void mainListView_KeyUp (object sender, KeyEventArgs e) {
            switch (e.KeyCode) {
                case Keys.Enter:
                    CopyPasswordToClipboard ();
                    break;
                case Keys.Space:
                    NavigateToURL ();
                    break;
            }
        } 

        private void mainListView_MouseDoubleClick (object sender, MouseEventArgs e) {
            CopyUserNameToClipboard ();
        }

        #endregion

        #region list view context menu event's

        private void cmMenuEditEditToolStripMenuItem_Click (object sender, EventArgs e) {
            menuEditEditToolStripMenuItem_Click (sender, e);
        }

        private void cmMenuEditAddToolStripMenuItem_Click (object sender, EventArgs e) {
            menuEditAddToolStripMenuItem_Click (sender, e);
        }

        private void cmMenuEditDelToolStripMenuItem_Click (object sender, EventArgs e) {
            menuEditDelToolStripMenuItem_Click (sender, e);
        }

        private void cmMenuEditDuplicateToolStripMenuItem_Click (object sender, EventArgs e) {
            menuEditDuplicateToolStripMenuItem_Click (sender, e);
        }

        private void cmMenuEditCopyUserToolStripMenuItem_Click (object sender, EventArgs e) {
            menuEditCopyUserToolStripMenuItem_Click (sender, e);
        }

        private void cmMenuEditCopyPasswordToolStripMenuItem_Click (object sender, EventArgs e) {
            menuEditCopyPasswordToolStripMenuItem_Click (sender, e);
        }

        private void cmMenuEditNavigateURLToolStripMenuItem_Click (object sender, EventArgs e) {
            menuEditNavigateURLToolStripMenuItem_Click (sender, e);
        }
        
        #endregion

        #region copy to clipboard helper's
        
        private void CopyUserNameToClipboard () {
            Guid selectedGuid = GetSelectedPasswordObject ();

            if (selectedGuid != Guid.Empty) {
                PasswordObject selectedPasswordObject = (PasswordObject)FindPasswordObject (selectedGuid).Clone ();

                Clipboard.SetText (selectedPasswordObject.UserName);
                ShowTimedStatusBarMessage (Properties.Resources.MainForm_StatusBarUserCopied);
            }
            else {
                MessageDialog.ShowError (this, Properties.Resources.MainForm_MsgSelectItemFirstError);
            }
        }

        private void CopyPasswordToClipboard () {
            Guid selectedGuid = GetSelectedPasswordObject ();

            if (selectedGuid != Guid.Empty) {
                PasswordObject selectedPasswordObject = (PasswordObject)FindPasswordObject (selectedGuid).Clone ();

                Clipboard.SetText (selectedPasswordObject.Password);
                ShowTimedStatusBarMessage (Properties.Resources.MainForm_StatusBarPassCopied);

                // save last copied password to check when click password occur
                _lastCopiedPassword = selectedPasswordObject.Password;
            }
            else {
                MessageDialog.ShowError (this, Properties.Resources.MainForm_MsgSelectItemFirstError);
            }
        }

        private void NavigateToURL () {
            Guid selectedGuid = GetSelectedPasswordObject ();

            if (selectedGuid != Guid.Empty) {
                PasswordObject selectedPasswordObject = (PasswordObject)FindPasswordObject (selectedGuid).Clone ();

                PassBag.Utils.WebTools.Navigate (selectedPasswordObject.Url);

                ShowTimedStatusBarMessage (Properties.Resources.MainForm_StatusBarNavigateURL);
            }
            else {
                MessageDialog.ShowError (this, Properties.Resources.MainForm_MsgSelectItemFirstError);
            }
        } 

        #endregion

        #region status bar message

        private void ShowTimedStatusBarMessage (string message) {
            // if timer enabled do nothing
            if (!statusBarMessageTimer.Enabled) {
                infoToolStripStatusLabel.Text = message;
                statusBarMessageTimer.Enabled = true;
            }
        }
        
        private void statusBarMessageTimer_Tick (object sender, EventArgs e) {
            statusBarMessageTimer.Enabled = false;
            infoToolStripStatusLabel.Text = string.Empty;
        } 

        #endregion

        #region recent files menu

        private void UpdateRecentFileList (string fileName) {
            _recentFile.Add (fileName);
            UpdateRecentFileMenu ();
        }

        private void MainForm_FormClosing (object sender, FormClosingEventArgs e) {
            SaveRecentFileMenu ();
        }

        private void InitRecentFileMenu () {
            _recentFile.Add (XmlSettingsManager.Settings.RecentOpenFile5);
            _recentFile.Add (XmlSettingsManager.Settings.RecentOpenFile4);
            _recentFile.Add (XmlSettingsManager.Settings.RecentOpenFile3);
            _recentFile.Add (XmlSettingsManager.Settings.RecentOpenFile2);
            _recentFile.Add (XmlSettingsManager.Settings.RecentOpenFile1);

            UpdateRecentFileMenu ();
        }

        private void UpdateRecentFileMenu () {
            if (_recentFile.Count () > 0) {
                menuFileOpenRecentToolStripMenuItem.Enabled = true;

                UpdateRecentFileMenuItem (_recentFile[0], menuFileOpenRecentFile1ToolStripMenuItem);
                UpdateRecentFileMenuItem (_recentFile[1], menuFileOpenRecentFile2ToolStripMenuItem);
                UpdateRecentFileMenuItem (_recentFile[2], menuFileOpenRecentFile3ToolStripMenuItem);
                UpdateRecentFileMenuItem (_recentFile[3], menuFileOpenRecentFile4ToolStripMenuItem);
                UpdateRecentFileMenuItem (_recentFile[4], menuFileOpenRecentFile5ToolStripMenuItem);

            }
            else {
                menuFileOpenRecentToolStripMenuItem.Enabled = false;

                UpdateRecentFileMenuItem (string.Empty, menuFileOpenRecentFile1ToolStripMenuItem);
                UpdateRecentFileMenuItem (string.Empty, menuFileOpenRecentFile2ToolStripMenuItem);
                UpdateRecentFileMenuItem (string.Empty, menuFileOpenRecentFile3ToolStripMenuItem);
                UpdateRecentFileMenuItem (string.Empty, menuFileOpenRecentFile4ToolStripMenuItem);
                UpdateRecentFileMenuItem (string.Empty, menuFileOpenRecentFile5ToolStripMenuItem);
            }
        }

        private void UpdateRecentFileMenuItem (string fileName, ToolStripMenuItem menuItem) {
            if (string.IsNullOrEmpty(fileName)) {
                menuItem.Visible = false;              
            }
            else {
                menuItem.Visible = true;
                menuItem.Text = fileName;
            }
        }

        private void SaveRecentFileMenu () {
            XmlSettingsManager.Settings.RecentOpenFile1 = _recentFile[0];
            XmlSettingsManager.Settings.RecentOpenFile2 = _recentFile[1];
            XmlSettingsManager.Settings.RecentOpenFile3 = _recentFile[2];
            XmlSettingsManager.Settings.RecentOpenFile4 = _recentFile[3];
            XmlSettingsManager.Settings.RecentOpenFile5 = _recentFile[4];
            XmlSettingsManager.Save ();
        }

        private void ClearRecentFileMenu () {
            _recentFile.Clear ();
            UpdateRecentFileMenu ();

            if (_showMode == ShowMode.RecentFile) {
                UpdateShowMode(ShowMode.RecentFile);
            }
        }
        
        #endregion

        #region filter items
        private void FilterItems (string filterText) {
            int startIndex = 0;
            ListViewItem foundItem = null;

            if (! _isFileEmpty) {
                try {
                    while (startIndex < mainListView.Items.Count && (foundItem = mainListView.FindItemWithText (filterText, true, startIndex, true)) != null) {

                        foundItem.UseItemStyleForSubItems = true;
                        foundItem.BackColor = BACK_FILTER_COLOR;
                        foundItem.ForeColor = FORE_FILTER_COLOR;

                        foundItem.Font = _filterItemFont;

                        startIndex = foundItem.Index + 1;
                    }

                }
                catch (ArgumentOutOfRangeException ex) {
                    MessageDialog.ShowError (this, ex.Message);
                } 
            }

        }

        private void ClearFilter () {
            filterToolStripTextBox.Clear ();

            foreach (ListViewItem item in mainListView.Items) {
                item.UseItemStyleForSubItems = true;

                item.BackColor = BACK_DEFAULT_COLOR;
                item.ForeColor = FORE_DEFAULT_COLOR;
                item.Font = _defaultItemFont;
            }

        } 

        
        private void InitFilterFont () {
            _defaultItemFont = mainListView.Font;
            _filterItemFont = new Font(_defaultItemFont, FontStyle.Bold);
        }
        #endregion

        #region show mode
        private void InitModeControls() {
            unlockFile.PasswordEntered +=new UnlockFileControl.EnterPasswordEventHandler(unlockFile_PasswordEntered);
            startPage.QueryFileOpen += new StartPageControl.OpenFileEventHandler(startPage_QueryFileOpen);
        }

        void startPage_QueryFileOpen(object sender, FileEventArgs e) {
            if (OpenDocument(e.RecentFile)) {
                UpdateShowMode(ShowMode.PasswordList);
                UpdateLockTimer();
            }
        }

        void unlockFile_PasswordEntered(object sender, PasswordEventArgs e) {
            if (e.Password.Equals(_filePassword)) {
                _isLocked = false;
                UpdateShowMode(ShowMode.PasswordList);
                UpdateLockTimer();
            }
            else if (string.IsNullOrEmpty(e.Password)) {
                unlockFile.MessageError = Properties.Resources.MainForm_UnlockStatusPassEmpty;
            }
            else {
                unlockFile.MessageError = Properties.Resources.MainForm_UnlockStatusBadPass;
            }
            //throw new NotImplementedException();
        }

        private void UpdateShowMode(ShowMode mode) {
            this.mainPanel.SuspendLayout();
            this.SuspendLayout();

            // remove current control
            switch (_showMode) {
                case ShowMode.RecentFile:
                    this.mainPanel.Controls.Remove(startPage);
                    startPage.Visible = false;
                    break;

                case ShowMode.Unlock:
                    this.mainPanel.Controls.Remove(unlockFile);
                    unlockFile.Visible = false;
                    break;

                case ShowMode.PasswordList:
                    this.mainPanel.Controls.Remove(mainListView);
                    //this.mainListView.Dock = System.Windows.Forms.DockStyle.None;
                    mainListView.Visible = false;
                    break;
            }

            // add new control
            switch (mode) {
                case ShowMode.RecentFile:
                    this.startPage.Clear();

                    for (int i = 0; i < 5; i++) {
                        this.startPage[i] = _recentFile[i];
                    }

                    this.startPage.Visible = true;
                    this.mainPanel.Controls.Add(startPage);
                    this.startPage.Dock = System.Windows.Forms.DockStyle.Fill;
                    this.startPage.Location = new System.Drawing.Point(0, 0);
                    this.startPage.Size = this.mainPanel.Size;
                    this.startPage.TabIndex = 0;
                    this.startPage.Refresh();

                    break;

                case ShowMode.Unlock:
                    this.unlockFile.Clear();

                    this.unlockFile.Visible = true;
                    this.mainPanel.Controls.Add(unlockFile);
                    this.unlockFile.Dock = System.Windows.Forms.DockStyle.Fill;
                    this.unlockFile.Location = new System.Drawing.Point(0, 0);
                    this.unlockFile.Size = this.mainPanel.Size;
                    this.unlockFile.TabIndex = 0;
                    this.unlockFile.Refresh();

                    break;

                case ShowMode.PasswordList:
                    _isLocked = false;
                    this.mainListView.Visible = true;
                    this.mainPanel.Controls.Add(mainListView);
                    this.mainListView.Dock = System.Windows.Forms.DockStyle.Fill;
                    this.mainListView.Location = new System.Drawing.Point(0, 0);
                    this.mainListView.Size = this.mainPanel.Size;
                    this.mainListView.TabIndex = 0;
                    this.mainListView.Refresh();

                    break;
            }

            _showMode = mode;

            this.mainPanel.ResumeLayout(false);
            this.ResumeLayout(false);

            ApplyMenuSettings();
        } 
        #endregion

        #region init lock timer

        private void UpdateLockTimer() {
            int lockAfterSeconds = XmlSettingsManager.Settings.GeneralLockAfterXSecond;

            lockTimer.Stop();

            if (! _isLocked && _isFileOpen) {
                if (lockAfterSeconds != 0) {
                    lockTimer.Interval = XmlSettingsManager.Settings.GeneralLockAfterXSecond * 1000;
                    lockTimer.Start();

                } 
            }
        }

        private void lockTimer_Tick(object sender, EventArgs e) {
            DoLock();
        }

        private void DoLock() {
            // if main for is the active form
            if (Form.ActiveForm.Equals(this) && !_isLocked && _isFileOpen) {
                _isLocked = true;
                UpdateShowMode(ShowMode.Unlock);

                if (XmlSettingsManager.Settings.GeneralClearClipboardOnLock) {
                    if (_lastCopiedPassword.Equals(Clipboard.GetText())) {
                        Clipboard.Clear();
                    }
                }
            }
            else { // the active form is About, edit, etc..
                UpdateLockTimer();
            }
        }

        private void MainForm_Resize(object sender, EventArgs e) {

            if (this.WindowState == FormWindowState.Minimized) {
                if (XmlSettingsManager.Settings.GeneralLockOnMinimize) {
                    DoLock();
                }
            }
        
        }
        #endregion
    }
}
